package com.blog.cloud.oss.dynamic.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClientBuilder;
import com.blog.cloud.oss.dynamic.properties.StorageProperties;
import com.blog.cloud.oss.dynamic.properties.StorageProperty;
import com.blog.cloud.oss.dynamic.service.StorageService;
import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.Objects;

@Slf4j
@EnableConfigurationProperties(StorageProperties.class)
@ConditionalOnProperty(prefix = StorageProperties.PREFIX, value = "enabled", havingValue = "true", matchIfMissing = false)
public class StorageConfig {

    @Bean
    public StorageService storageService(StorageProperties properties) {
        if (Objects.isNull(properties.getPrimary())) {
            log.warn("primary storage must be specified,please set the primary");
            return null;
        }

//        if (properties.getPrimary() == StorageType.LOCAL) {
//            return null;
//        } else if (properties.getPrimary() == StorageType.ALIYUN) {
//            return null;
//        } else if (properties.getPrimary() == StorageType.TENCENT) {
//            return null;
//        }
        return null;
    }

    @Bean
    @ConditionalOnProperty(prefix = StorageProperties.PREFIX, value = "primary", havingValue = "aliyun")
    public OSS ossClient(StorageProperties properties) {
        OSSBuilder builder = new OSSClientBuilder();
        StorageProperty config = properties.getSourceName().get("aliyun");
        return builder.build(config.getAccessKey(), config.getSecretKey(), config.getEndpoint());
    }

    @Bean
    @ConditionalOnProperty(prefix = StorageProperties.PREFIX, value = "primary", havingValue = "tencent")
    public COS cosClient(StorageProperties properties) {
        StorageProperty config = properties.getSourceName().get("tencent");
        COSCredentials cred = new BasicCOSCredentials(config.getAccessKey(), config.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(config.getEndpoint()));
        return new COSClient(cred, clientConfig);
    }

}
